package com.xh.web.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xh.web.constant.Constants;
import com.xh.web.domain.DColumn;
import com.xh.web.domain.DGenTable;
import com.xh.web.domain.DGenTableColumn;
import com.xh.web.domain.DTable;
import com.xh.web.exception.CustomException;
import com.xh.web.mapper.DColumnMapper;
import com.xh.web.mapper.DTableMapper;
import com.xh.web.mapper.DbGenTableColumnMapper;
import com.xh.web.mapper.DbGenTableMapper;
import com.xh.web.service.IDbGenTableService;
import com.xh.web.util.*;
import com.xh.web.util.file.FileUtils;
import com.xh.web.util.velocity.VelocityInitializer;
import com.xh.web.util.velocity.VelocityUtils;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 业务 服务层实现
 *
 * @author ruoyi
 */
@Service
public class DbGenTableServiceImpl implements IDbGenTableService
{
    private static final Logger log = LoggerFactory.getLogger(DbGenTableServiceImpl.class);

    @Autowired
    private DbGenTableMapper genTableMapper;

    @Autowired
    private DbGenTableColumnMapper genTableColumnMapper;

    @Autowired
    private DColumnMapper dColumnMapper;
    @Autowired
    private DTableMapper dTableMapper;

    /**
     * 查询业务信息
     *
     * @param id 业务ID
     * @return 业务信息
     */
    @Override
    public DGenTable selectGenTableById(String id)
    {
        DGenTable genTable = genTableMapper.selectGenTableById(id);
        setTableFromOptions(genTable);
        return genTable;
    }

    /**
     * 查询业务列表
     *
     * @param genTable 业务信息
     * @return 业务集合
     */
    @Override
    public List<DGenTable> selectGenTableList(DGenTable genTable)
    {
        return genTableMapper.selectGenTableList(genTable);
    }



    /**
     * 修改业务
     *
     * @param genTable 业务信息
     * @return 结果
     */
    @Override
    @Transactional
    public void updateGenTable(DGenTable genTable)
    {
        String options = JSON.toJSONString(genTable.getParams());
        genTable.setOptions(options);
        try {
            List<DGenTableColumn> columns=genTable.getColumns();

            //SysUser user = SecurityUtils.getLoginUser().getUser();
            genTable.setUpdateBy("admin");
            genTable.setUpdateTime(new Date());
            int row = genTableMapper.updateGenTable(genTable);
          if (row > 0)
        {
                for (DGenTableColumn cenTableColumn : columns)
                {
                    cenTableColumn.setUpdateBy("admin");
                    cenTableColumn.setUpdateTime(new Date());
                   int columnSum= genTableColumnMapper.updateGenTableColumn(cenTableColumn);
               }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 导入表结构
     *
     * @param
     */
    @Override
    @Transactional
    public void importGenTable(DGenTable genTable)
    {
        //String operName = SecurityUtils.getUsername();
        try
        {
            DTable dTable= dTableMapper.selectDTableById(genTable.getTableId());
                GenUtils.initTableDB(genTable,"admin",dTable);
                genTable.setCreateTime(DateUtils.getNowDate());
                int row = genTableMapper.insertGenTable(genTable);
                if (row > 0)
                {
                    // 保存列信息
                    List<DColumn> dColumns = dColumnMapper.selectByTableId(genTable.getTableId());
                    genTableColumnMapper.deleteGenTableColumnByTableId(genTable.getTableId());
                    for (DColumn dcolumn : dColumns)
                    {
                        DGenTableColumn dGenTableColumn=new DGenTableColumn();
                        GenUtils.initColumnFieldDB(dGenTableColumn, dcolumn);
                        dGenTableColumn.setCreateTime(DateUtils.getNowDate());
                        genTableColumnMapper.insertGenTableColumn(dGenTableColumn);
                    }
                }
        }
        catch (Exception e)
        {
            throw new CustomException("导入失败：" + e.getMessage());
        }
    }

    /**
     * 预览代码
     *
     * @param tableId 表编号
     * @return 预览数据列表
     */
    @Override
    public Map<String, String> previewCode(String tableId)
    {
        Map<String, String> dataMap = new LinkedHashMap<>();
        // 查询表信息
        DGenTable table = genTableMapper.selectGenTableById(tableId);
        // 查询列信息
        List<DGenTableColumn> columns = genTableColumnMapper.selectGenTableColumnListByTableId(tableId);
        setPkColumn(table, columns);
        VelocityInitializer.initVelocity();

        VelocityContext context = GenUtils.prepareContextDB(table,columns);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateJavaList(table.getTplCategory());
        for (String template : templates)
        {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Constants.UTF8);
            tpl.merge(context, sw);
            dataMap.put(template, sw.toString());
        }
        return dataMap;
    }

    /**
     * 生成代码（下载方式）
     *
     * @param tableId 表名称
     * @return 数据
     */
   /* @Override
    public byte[] downloadCode(String tableId)
    {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        generatorCode(tableId, zip);
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }*/

    /**
     * 生成代码（自定义路径）
     *
     * @param
     * @return 数据
     */
    @Override
    public void generatorCode(String tableId)
    {
        // 查询表信息
        DGenTable table = genTableMapper.selectGenTableByName(tableId);
        // 查询列信息
       List<DGenTableColumn> columns= genTableColumnMapper.selectGenTableColumnListByTableId(tableId);
        setPkColumn(table, columns);
        VelocityInitializer.initVelocity();

        VelocityContext context = GenUtils.prepareContextDB(table,columns);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateJavaList(table.getTplCategory());
        for (String template : templates)
        {
           // if (!StringUtils.containsAny(template))
           // {
                // 渲染模板
                StringWriter sw = new StringWriter();
                Template tpl = Velocity.getTemplate(template, Constants.UTF8);
                tpl.merge(context, sw);
                try
                {
                    String path = getGenPath(table, template);
                    FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8);
                }
                catch (IOException e)
                {
                    throw new CustomException("渲染模板失败，表名：" + table.getTableName());
                }
            }
        //}
    }

    /**
     * 批量生成代码（下载方式）
     *
     * @param
     * @return 数据
     */
    @Override
    public byte[] downloadCode(String tableId)
    {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

            generatorCode(tableId, zip);

        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    /**
     * 查询表信息并生成代码
     */
    private void generatorCode(String tableId, ZipOutputStream zip)
    {
        // 查询表信息
        DGenTable table = genTableMapper.selectGenTableByName(tableId);
        // 查询列信息
        List<DGenTableColumn> columns = genTableColumnMapper.selectGenTableColumnListByTableId(tableId);
        setPkColumn(table, columns);

        VelocityInitializer.initVelocity();

        VelocityContext context = GenUtils.prepareContextDB(table,columns);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateJavaList(table.getTplCategory());
        for (String template : templates)
        {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Constants.UTF8);
            tpl.merge(context, sw);
            try
            {
                // 添加到zip
                zip.putNextEntry(new ZipEntry(GenUtils.getFileNameDB(template, table)));
                IOUtils.write(sw.toString(), zip, Constants.UTF8);
                IOUtils.closeQuietly(sw);
				zip.flush();
                zip.closeEntry();
            }
            catch (IOException e)
            {
                log.error("渲染模板失败，表名：" + table.getTableName(), e);
            }
        }
    }

    /**
     * 修改保存参数校验
     *
     * @param genTable 业务信息
     */
    @Override
    public void validateEdit(DGenTable genTable)
    {
        if (GenConstants.TPL_TREE.equals(genTable.getTplCategory()))
        {
            String options = JSON.toJSONString(genTable.getParams());
            JSONObject paramsObj = JSONObject.parseObject(options);
            if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE)))
            {
                throw new CustomException("树编码字段不能为空");
            }
            else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE)))
            {
                throw new CustomException("树父编码字段不能为空");
            }
            else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME)))
            {
                throw new CustomException("树名称字段不能为空");
            }
        }
    }

    /**
     * 设置主键列信息
     *
     * @param table 业务表信息
     * @param columns 业务字段列表
     */
    public void setPkColumn(DGenTable table, List<DGenTableColumn> columns)
    {
        for (DGenTableColumn column : columns)
        {
            if (column.isPk())
            {
                table.setPkColumn(column);
                break;
            }
        }
        if (StringUtils.isNull(table.getPkColumn()))
        {
            table.setPkColumn(columns.get(0));
        }
    }

    /**
     * 设置代码生成其他选项值
     *
     * @param genTable 设置后的生成对象
     */
    public void setTableFromOptions(DGenTable genTable)
    {
        JSONObject paramsObj = JSONObject.parseObject(genTable.getOptions());
        if (StringUtils.isNotNull(paramsObj))
        {
            String treeCode = paramsObj.getString(GenConstants.TREE_CODE);
            String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE);
            String treeName = paramsObj.getString(GenConstants.TREE_NAME);
            String parentMenuId = paramsObj.getString(GenConstants.PARENT_MENU_ID);
            String parentMenuName = paramsObj.getString(GenConstants.PARENT_MENU_NAME);

            genTable.setTreeCode(treeCode);
            genTable.setTreeParentCode(treeParentCode);
            genTable.setTreeName(treeName);
            genTable.setParentMenuId(parentMenuId);
            genTable.setParentMenuName(parentMenuName);
        }
    }

    /**
     * 获取代码生成地址
     *
     * @param table 业务表信息
     * @param template 模板文件路径
     * @return 生成地址
     */
    public static String getGenPath(DGenTable table, String template)
    {
        String genPath = table.getGenPath();
        if (StringUtils.equals(genPath, "/"))
        {
            return System.getProperty("user.dir") + File.separator + "src" + File.separator + GenUtils.getFileNameDB(template, table);
        }
        return genPath + File.separator + GenUtils.getFileNameDB(template, table);
    }


    public DGenTable selGenTableByTableId(String tableId){
        return genTableMapper.selGenTableByTableId(tableId);
    };

    /**
     * 删除业务信息
     *
     * @param tableId 表id
     * @return 结果
     */
    public int deleteGenTableById(String tableId) {
  return genTableMapper.deleteGenTableById(tableId);
    }
}
